package se.statifyme.server.store;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;

import se.statifyme.shared.HasId;

import com.google.inject.Inject;

public class AbstractStore<E extends HasId> {
	
	@Inject
	private EntityManagerFactory managerFactory;
	
	protected final String TYPE;
	protected final Class<E> entityClass;
	
	public AbstractStore(Class<E> entityClass) {
		if (entityClass == null) {
			throw new IllegalArgumentException("Entity class must not be null");
		}
		this.entityClass = entityClass;
		this.TYPE = entityClass.getSimpleName();
	}
	
	protected E get(String id) {
		EntityManager manager = getManager();
		E result;
		try {
			result = manager.find(entityClass, id);
		} finally {
			manager.close();
		}

		return result;
	}
	
	protected void save(E entity) {
		EntityManager manager = getManager();
		try {
			manager.persist(entity);
		} finally {
			manager.close();
		}
	}
	
	protected void delete(String id) {
		EntityManager manager = getManager();
		try {
			E entity = manager.find(entityClass, id);
			manager.remove(entity);
		} finally {
			manager.close();
		}
	}
	
	protected EntityManagerFactory getManagerFactory() {
		return managerFactory;
	}

	protected void setManagerFactory(EntityManagerFactory managerFactory) {
		this.managerFactory = managerFactory;
	}

	protected EntityManager getManager() {
		EntityManagerFactory managerFactory = getManagerFactory();
		
		return managerFactory.createEntityManager();
	}
}
